package com.nbsaas.boot;

import java.math.BigInteger;

public class EightBitPermission {

    private static final int BIT_LENGTH = 8;
    private BigInteger bits = BigInteger.ZERO;

    public EightBitPermission() {}

    public EightBitPermission(String binaryString) {
        if (binaryString.length() != BIT_LENGTH || !binaryString.matches("[01]+")) {
            throw new IllegalArgumentException("必须是8位二进制字符串");
        }
        this.bits = new BigInteger(binaryString, 2);
    }

    // 授予某个权限位
    public void grantPermission(int index) {
        validateIndex(index);
        bits = bits.setBit(index);
    }

    // 撤销某个权限位
    public void revokePermission(int index) {
        validateIndex(index);
        bits = bits.clearBit(index);
    }

    // 判断是否拥有某个权限位
    public boolean hasPermission(int index) {
        validateIndex(index);
        return bits.testBit(index);
    }

    // 获取8位二进制字符串（如 01000001）
    public String getBinaryValue() {
        System.out.println("二进制：" + String.format("%8s", bits.toString(2)));
        return String.format("%8s", bits.toString(2)).replace(' ', '0');
    }

    // 获取十进制权限值
    public int getNumericValue() {
        return bits.intValue();
    }

    // 设置权限值（从 int）
    public void setValue(int value) {
        this.bits = BigInteger.valueOf(value);
    }

    private void validateIndex(int index) {
        if (index < 0 || index >= BIT_LENGTH) {
            throw new IllegalArgumentException("权限位必须在 0~7 之间");
        }
    }
}
